const { Notification, User } = require('./model');
const { Op } = require('sequelize');

class NotificationDao {
  // 创建通知
  async createNotification(notificationData) {
    try {
      return await Notification.create(notificationData);
    } catch (error) {
      throw new Error(`创建通知失败: ${error.message}`);
    }
  }

  // 批量创建通知
  async createBulkNotifications(notificationsData) {
    try {
      const notifications = await Notification.bulkCreate(notificationsData);
      return notifications.length;
    } catch (error) {
      throw new Error(`批量创建通知失败: ${error.message}`);
    }
  }

  // 根据ID查找通知
  async getNotificationById(id) {
    try {
      return await Notification.findByPk(id);
    } catch (error) {
      throw new Error(`查找通知失败: ${error.message}`);
    }
  }

  // 根据ID数组查找通知
  async getNotificationsByIds(ids) {
    try {
      return await Notification.findAll({
        where: {
          id: {
            [Op.in]: ids
          }
        }
      });
    } catch (error) {
      throw new Error(`批量查找通知失败: ${error.message}`);
    }
  }

  // 获取用户通知列表（分页）
  async getUserNotifications(options) {
    try {
      const { user_id, type, is_read, page = 1, limit = 10 } = options;
      const offset = (page - 1) * limit;
      const where = { user_id };

      // 构建查询条件
      if (type) {
        where.type = type;
      }
      if (is_read !== undefined) {
        where.is_read = is_read;
      }

      const { count, rows } = await Notification.findAndCountAll({
        where,
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: parseInt(offset)
      });

      return {
        notifications: rows,
        total: count,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(count / limit)
      };
    } catch (error) {
      throw new Error(`获取用户通知列表失败: ${error.message}`);
    }
  }

  // 标记通知为已读
  async markAsRead(notificationId) {
    try {
      const [affectedRows] = await Notification.update(
        { 
          is_read: true,
          read_at: new Date()
        },
        {
          where: { id: notificationId }
        }
      );
      return affectedRows > 0;
    } catch (error) {
      throw new Error(`标记通知为已读失败: ${error.message}`);
    }
  }

  // 批量标记通知为已读
  async markMultipleAsRead(notificationIds) {
    try {
      const [affectedRows] = await Notification.update(
        { 
          is_read: true,
          read_at: new Date()
        },
        {
          where: {
            id: {
              [Op.in]: notificationIds
            }
          }
        }
      );
      return affectedRows;
    } catch (error) {
      throw new Error(`批量标记通知为已读失败: ${error.message}`);
    }
  }

  // 标记用户所有通知为已读
  async markAllAsReadForUser(userId) {
    try {
      const [affectedRows] = await Notification.update(
        { 
          is_read: true,
          read_at: new Date()
        },
        {
          where: {
            user_id: userId,
            is_read: false
          }
        }
      );
      return affectedRows;
    } catch (error) {
      throw new Error(`标记所有通知为已读失败: ${error.message}`);
    }
  }

  // 删除通知
  async deleteNotification(notificationId) {
    try {
      const affectedRows = await Notification.destroy({
        where: { id: notificationId }
      });
      return affectedRows > 0;
    } catch (error) {
      throw new Error(`删除通知失败: ${error.message}`);
    }
  }

  // 批量删除通知
  async deleteMultipleNotifications(notificationIds) {
    try {
      const affectedRows = await Notification.destroy({
        where: {
          id: {
            [Op.in]: notificationIds
          }
        }
      });
      return affectedRows;
    } catch (error) {
      throw new Error(`批量删除通知失败: ${error.message}`);
    }
  }

  // 获取用户未读通知数量
  async getUnreadCount(userId) {
    try {
      return await Notification.count({
        where: {
          user_id: userId,
          is_read: false
        }
      });
    } catch (error) {
      throw new Error(`获取未读通知数量失败: ${error.message}`);
    }
  }

  // 获取通知统计
  async getNotificationStats(userId) {
    try {
      const total = await Notification.count({
        where: { user_id: userId }
      });

      const unread = await Notification.count({
        where: {
          user_id: userId,
          is_read: false
        }
      });

      // 按类型统计
      const typeStats = await Notification.findAll({
        where: { user_id: userId },
        attributes: [
          'type',
          [Notification.sequelize.fn('COUNT', Notification.sequelize.col('id')), 'count']
        ],
        group: ['type'],
        raw: true
      });

      const stats = {
        total,
        unread,
        system_count: 0,
        course_count: 0,
        game_count: 0,
        daily_count: 0,
        social_count: 0
      };

      // 处理类型统计
      typeStats.forEach(stat => {
        stats[`${stat.type}_count`] = parseInt(stat.count);
      });

      return stats;
    } catch (error) {
      throw new Error(`获取通知统计失败: ${error.message}`);
    }
  }

  // 清理过期通知（可选功能）
  async cleanupExpiredNotifications(daysOld = 30) {
    try {
      const cutoffDate = new Date();
      cutoffDate.setDate(cutoffDate.getDate() - daysOld);

      const affectedRows = await Notification.destroy({
        where: {
          created_at: {
            [Op.lt]: cutoffDate
          },
          is_read: true
        }
      });

      return affectedRows;
    } catch (error) {
      throw new Error(`清理过期通知失败: ${error.message}`);
    }
  }
}

module.exports = new NotificationDao();
